import pymysql
import sqlalchemy
from sqlalchemy import create_engine, or_
from functools import wraps
from flask import jsonify, request

engine = create_engine('mysql+pymysql://root:mysql@localhost:3306/cmdb/charset=utf8')


def exception_catch(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        try:
            result = func(*args, **kwargs)
        except Exception as e:
            return jsonify({'code': 4000, 'error': str(e)})
        return result
    return wrapper


def page_search_order_filter(request, model):
    page = request.args.get('page', 1)
    size = request.args.get('size', 10)
    order = request.args.get('order', 'id')
    filter_dict = request.args.get('filter', {})
    search_dict = request.args.get('search', {})

    try:
        page, size = int(page), int(size)
    except TypeError as e:
        return jsonify({'code': -1, 'data': [], 'info': 'error', 'error': 'page/size非法参数'})

    queryset = model.query
    if filter_dict:
        queryset = model.query.filter(**filter_dict)
    if search_dict:
        queryset = model.query.filter(or_())
    queryset = queryset.order_by(order).paginate(page, size, False).items
    count = len(queryset)
    return queryset, count


import json

from decimal import Decimal
from datetime import datetime
from datetime import date


class CZJsonEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, datetime):
            return obj.strftime('%Y-%m-%d %H:%M:%S')
        elif isinstance(obj, date):
            return obj.strftime('%Y-%m-%d')
        elif isinstance(obj, Decimal):
            # return str(obj)
            return float(obj)
        else:
            return json.JSONEncoder.default(self, obj)
